package com.cy.milktea.pojo;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.io.Serializable;
import java.util.List;

@Data
public class Goods implements Serializable {

    private static final long serialVersionUID = 6849794400754997352L;

    private Drink drink;  //-------------->顾客所选的饮品 包括饮品对应的配料
    private Integer count;  //------------>顾客选的数量, 饮品所选中所有属性相同才是同一个商品
    private Long cost = 0L;  //----------->商品的总价格(饮品价格 + 所选的配料价格)

    private String drinkDesc;  //--------->饮品描述

    private boolean isTotalCost = true;  //------>是否已经计算了价格,已经计算了为false,未计算为true




    /* 计算商品价格 */
    public Long totalCost() {
        // 判断是否已经计算了价格
        if (isTotalCost) {
            isTotalCost = false;
            Long cost = this.drink.getPrice();
            List<Entremets> entremetsLis = this.drink.getEntremetsList();
            if (entremetsLis != null && entremetsLis.size() != 0) {
                for (Entremets entremets : entremetsLis) {
                    cost += entremets.getPrice();
                }
            }
            this.cost = cost * count; //计算数量
        }
        return this.cost;
    }

    /* 将Drink对象json序列化成DrinkDesc */
    public void createDrinkDesc() {
        try {
            drinkDesc = new ObjectMapper().writeValueAsString(drink);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
    /* 将DrinkDesc的json字符串反序列化成Drink */
    public void unJsonToDrink() {
        if (drink == null && drinkDesc != null) {
            try {
                drink = new ObjectMapper().readValue(drinkDesc, Drink.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException("drinkDesc初始值异常!");
            }
        } else {
            throw new RuntimeException("drink或drinkDesc初始值异常!");
        }
    }

}
